# coding=utf-8

from construct import *
from struct import unpack

BNET_HEADER_CONSTANT = "\xff"

SID_GETADVLISTEX = 0x09

class FreeSlotAdapter(Adapter):

    charToInt =   { "0" : 0, "1" : 0, "2" : 1, "3" : 2, "4" : 3, "5" : 4,
                    "6" : 5, "7" : 6, "8" : 7, "9" : 8, "a" : 9, "b" : 10,
                    "c" : 11, "d" : 12, "e" : 13, "f" : 14 }

    intToChar = dict([(v, k) for k, v in charToInt.iteritems()])
                    
    def _encode(self, obj, context):
        return ord(self.intToChar[obj])
 
    def _decode(self, obj, context):
        return self.charToInt[chr(obj)]

GETADVLISTEX = Struct("GetAdvListEx",
                        ULInt32("NumGames"),
                        IfThenElse("data", lambda ctx: ctx["NumGames"] > 0,
                            MetaRepeater(lambda ctx: ctx["NumGames"],
                             Struct("GameAnnounce",
                                ULInt32("GameType"),
                                ULInt32("LanguageID"),
                                ULInt16("AddrFamily"),
                                ULInt16("Port"),
                                ULInt32("HostIp"),
                                ULInt32("sin_zero1"),
                                ULInt32("sin_zero2"),
                                ULInt32("PubPrivate"), #(DWORD) Unknown (Public = 0x10, Private = 0x11)
                                ULInt32("ElapsedGameTime"),
                                CString("GameName"),
                                CString("GamePassword"), # always empty
                                FreeSlotAdapter(Byte("FreeSlots")),     #(BYTE) Free slots (character representing hexadecimal number)
                                String("HostCounter", 8),
                                CString("MapInfo") #encoded
                             )
                            ),
                            ULInt32("Status")
                        )
                    )

class ProtocolError(Exception):
    pass